<?php
namespace src\logic;
use \classlib\core as C;
class lsocial {
	const SpotCd = "W";
	/**
	 * POST 请求注册生成一个账号
	 * @param $email string
	 * @param $password string
	 * @param string $firstName
	 * @param string $lastName
	 * @return array(userId,token)
	 */
	public static function register($email, $password, $firstName=' ', $lastName=' ') {
		$conf   = config::load('psocial', false);
		if (empty($firstName)) {
			$firstName = ' ';
		}
		if (empty($lastName)) {
			$lastName = ' ';
		}
		$qrystr = array('email'=>$email, 'firstName'=>$firstName, 'lastName'=>$lastName,
				'pwd'=>$password, 'spotCd'=>self::SpotCd);
		$url    = $conf['psapi'].'/user/?'.http_build_query($qrystr);
		$res    = self::requst($url, 'POST');
		return $res;
	}
	
	/**
	 * POST 登录账号密码校验
	 * @param unknown $email
	 * @param unknown $password
	 * @return array
	 */
	public static function login($email, $password) {
		$conf   = C\config::load('psocial', false);
		$qrystr = array('email'=>$email, 'pwd'=>$password, 'spotCd'=>self::SpotCd);
		$url    = $conf['psapi'].'/login/?'.http_build_query($qrystr);
		$res    = self::requst($url, 'POST');
		return $res;
	}
	
	/**
	 * PUT 更新会员的邮箱或者密码
	 * @param $token string
	 * @param $email string
	 * @param $password string
	 * @param array $attachs
	 * @return array(userId,token)
	 */
	public static function save($token, $email, $password, $attachs=array()) {
		$conf   = C\config::load('psocial', false);
		$qrystr = array('token'=>$token, 'spotCd'=>self::SpotCd);
		if ($email) {
			$qrystr['email'] = $email;
		}
		if ($password) {
			$qrystr['pwd']   = $password;
		}
		if (is_array($attachs) && !empty($attachs)) {
			$qrystr += $attachs;
		}
		$url    = $conf['psapi'].'/user/?'.http_build_query($qrystr);
		$res    = self::requst($url, 'PUT');
		return $res;
	}
	
	/**
	 * 通过请求的token获取用户信息
	 * @param string $token
	 * @return array
	 */
	public static function getuser($token) {
		$conf   = C\config::load('psocial', false);
		$qrystr = array('token'=>$token, 'spotCd'=>self::SpotCd);
		$url    = $conf['psapi'].'/user/?'.http_build_query($qrystr);
		$res    = self::requst($url, 'GET');
		return $res;
	}
	
	/**
	 * GET 验证一个邮箱是否被注册
	 * @param unknown $email
	 * @return bool true 不存在 false 已经存在
	 */
	public static function checkemail($email) {
		$conf = C\config::load('psocial', false);
		$url  = $conf['psapi'].sprintf('/user/checkemail/%s/', $email);
		$res  = self::requst($url, 'GET');
		return $res;
	}
	
	/**
	 * 通过邮箱获取会员基础资料信息
	 * @param string $email
	 * @return array
	 **/
	public static function getbyemail($email) {
		$conf   = C\config::load('psocial', false);
		$url    = $conf['psapi'].sprintf('/plive/user/email/%s/?', $email);
		$tns    = self::microsec();
		$hs     = md5($conf['skey'].$tns.$email.self::SpotCd);
		$qrystr = array('email'=>$email, 'hs'=>$hs, 'ts'=>$tns, 'spotCd'=>uc_api::SpotCd);
		$url    = $url.http_build_query($qrystr);
		$res    = self::requst($url, 'GET');
		return $res;
	}
	
	/**
	 * PUT 保持邮箱验证的状态
	 * @param unknown $token
	 * @param unknown $verified
	 * @return bool true 不存在 false 已经存在
	 */
	public static function verifyemail($token, $verified=true) {
		$conf   = C\config::load('psocial', false);
		$qrystr = array('token'=>$token, 'verified'=>$verified, 'spotCd'=>self::SpotCd);
		$url    = $conf['psapi'].'/user/emailverify/?'.http_build_query($qrystr);
		$res    = self::requst($url, 'PUT');
		return $res;
	}
	
	/**
	 * POST使用FB用作登录使用
	 * @param string $token facebook return access token
	 * @return
	 */
	public static function fb_login($fbtoken) {
		$conf   = C\config::load('psocial', false);
		$qrystr = array('token'=>$fbtoken, 'spotCd'=>self::SpotCd);
		$url    = $conf['psapi'].'/social/fb/signup?'.http_build_query($qrystr);
		$res    = self::requst($url, 'POST');
		return $res;
	}
	
	/**
	 * POST完成FB与已经存在的账号绑定
	 * @param string $fbtoken
	 * @param string $token
	 */
	public static function fb_link($fbtoken, $token) {
		$conf   = C\config::load('psocial', false);
		$qrystr = array('fbtoken'=>$fbtoken, 'token'=>$token, 'spotCd'=>self::SpotCd);
		$url    = $conf['psapi'].'/social/fb/connect?'.http_build_query($qrystr);
		$res    = self::requst($url, 'POST');
		return $res;
	}
	
	/**
	 * 第三方账号取消绑定
	 * @param string $fbtoken
	 * @param string $token
	 */
	public static function disconnect($token, $uin, $type='Facebook') {
		$conf   = C\config::load('psocial', false);
		$ts     = self::microsec();
		$hs     = md5($conf['skey'].$ts.$uin);
		$qrystr = array('token'=>$token, 'type'=>$type, 'ts'=>$ts, 'hs'=>$hs, 'spotCd'=>self::SpotCd);
		$url    = $conf['psapi'].'/social/fb/disconnect/?'.http_build_query($qrystr);
		$res    = self::requst($url, 'DELETE');
		return $res;
	}
	
	/**
	 * 获取经过的毫秒数
	 * @return number
	 */
	public static function microsec() {
		list($msec, $sec) = explode(' ', microtime());
		return $sec * 1000 + intval($msec*1000);
	}

	/**
	 * 发起Http请求
	 * @param string $url
	 * @param string $method
	 * @param string $qrystr
	 * @param array  $header
	 * @param int    $timeout
	 * @param bool   $CA
	 * @return mix   $ret 错误返回array('result'=>errno, 'message'=>error, 'value'=>[])
	 */
	public static function requst($url, $method='POST', $qrystr='', $header=array(), $timeout=15, $CA=FALSE) {
		$ssl     = (strncasecmp('https', $url, 5) == 0)? true:false;
		$ch      = curl_init();
		$options = array(CURLOPT_HEADER=>false, CURLOPT_RETURNTRANSFER=>true,
				CURLOPT_CUSTOMREQUEST=>$method, CURLOPT_CONNECTTIMEOUT=>3, CURLOPT_TIMEOUT=>$timeout);
		if (strcasecmp($method, 'GET') == 0) {
			if ($qrystr) {
				$url .= '?'.$qrystr;
			}
		} else {
			$options[CURLOPT_POSTFIELDS] = empty($qrystr)? '{}':$qrystr;
		}
		if ($ssl && $CA) {
			$cacert = getcwd() . '/cacert.pem'; //CA根证书
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);   //只信任CA颁布的证书
			curl_setopt($ch, CURLOPT_CAINFO, $cacert); //CA根证书（用来验证的网站证书是否是CA颁布）
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); //检查证书中是否设置域名，并且是否与提供的主机名匹配
		} else if ($ssl && !$CA) {
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //信任任何证书
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); //检查证书中是否设置域名
		}
		$options[CURLOPT_URL] = $url;
		curl_setopt_array($ch, $options);
		$ret = curl_exec($ch);
		$err = curl_error($ch);
		$code= curl_getinfo($ch, CURLINFO_HTTP_CODE);
		$res = null;
		$lang= C\lang::inst('web');
		if ($code != 200 || false === $ret || !empty($err)) {
			$errno = curl_errno($ch);
			if (!$errno) {
				$errno = $code;
				$err   = $ret;
			}
			$res = array('result'=>$errno, 'message'=>$lang->txt('core', '504'));
		} else {
			$res = json_decode($ret, true);
		}
		//记录错误的日志
		if ($res['result'] != '000') {
			\classlib\logger::inst()->write($res['result'].':'.$res['message'].':'.$url);
			if ($res['result'] == '999') {
				$res['message'] = $lang->txt('core', '504');
			}
		}
		curl_close($ch);
		return $res;
	}
}